package com.example.safeassistan.utile;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class NewSurfaceView extends View {
    private Bitmap canvasBitmap = null;
    private Canvas canvas = null;

    public NewSurfaceView(Context context) {
        super(context);
    }

    public NewSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NewSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.i("宽,高", String.format("getMeasuredWidth: %d, getMeasuredHeight: %d", getMeasuredWidth(), getMeasuredHeight()));
        if (canvasBitmap == null) {
            canvasBitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
            canvas = new Canvas(canvasBitmap);
        } else {
            if (getMeasuredWidth() != canvasBitmap.getWidth() || getMeasuredHeight() != canvasBitmap.getHeight()) {
                canvasBitmap.recycle();
                canvasBitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
                canvas = new Canvas(canvasBitmap);
            }
        }
    }

    public void drawColor(int color) {
        canvas.drawColor(color);
        invalidate();
    }

    public void drawPath(Path path, Paint paint) {
        canvas.drawPath(path, paint);
        invalidate();
    }

    public void drawPath(Path path, Paint paint, Rect dirty) {
        canvas.drawPath(path, paint);
        invalidate(dirty);
    }

    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
        canvas.drawBitmap(bitmap, left, top, paint);
        invalidate();
    }

    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
        canvas.drawBitmap(bitmap, src, dst, paint);
        invalidate();
    }

    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
        canvas.drawBitmap(bitmap, src, dst, paint);
        invalidate();
    }

    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
        canvas.drawBitmap(bitmap, matrix, paint);
        invalidate();
    }

//    public void translate(float dx, float dy) {
//        Camera camera = new Camera();
//        camera.translate(dx,dy, 0);
//        camera.applyToCanvas(canvas);
//        invalidate();
//    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(canvasBitmap, 0f, 0f, null);
    }
}
